#include "stdafx.h"
#include "UboMaterial.h"
#include "common.h"

UboMaterial::UboMaterial() : UniformBufferObject(GL_DYNAMIC_DRAW)
{
	for (auto &off : m_offsets) off = -1;
}

UboMaterial::~UboMaterial()
{
}

void UboMaterial::QueryOffset(GLuint program)
{
	char *names[uo_count] = { "lightIndex", "materialParams.ambient", "lightParams[0].ambient", "lightParams[1].ambient" };
	int indices[uo_count];
	glGetUniformIndices(program, uo_count, names, (GLuint*)indices);
	glGetActiveUniformsiv(program, uo_count, (GLuint*)indices, GL_UNIFORM_OFFSET, m_offsets);
	for (int i = 0; i < uo_count; i++)
	{
		if (m_offsets[i] == -1) Exit("shader QueryOffset error: %s", names[i]);
	}
	m_lightParams_size = m_offsets[uo_lightParams1_ambient] - m_offsets[uo_lightParams0_ambient];
}

void UboMaterial::SetMaterial(MaterialParams *mate, bool bind)
{
	SetBufferData(m_offsets[uo_materialParams_ambient], sizeof(MaterialParams), mate, bind);
}

void UboMaterial::UseLight(int index, bool bind)
{
	SetBufferData(m_offsets[uo_lightIndex], sizeof(int), &index, bind);
}

void UboMaterial::SetLight(int index, LightParams &light, bool bind)
{
	SetBufferData(m_offsets[uo_lightParams0_ambient] + index*m_lightParams_size, sizeof(LightParams), &light, bind);
}